package HandshakeJoin;

import java.util.ArrayList;
import java.util.Calendar;
import com.google.common.collect.Lists;
import com.google.common.base.Joiner;

public class Tuple implements Comparable<Tuple>
{
    private int targetFieldIdx = 0;
    private long appearTime;
    private long expireTime = -1;
    private ArrayList<Integer> fields;
    private long seq;

    public Tuple(final int[] tuple, final long seq) {
        fields = Lists.newArrayListWithCapacity(tuple.length);
        for (int i = 0; i < tuple.length; ++i) {
            fields.add(tuple[i]);
        }

        this.seq = seq;

        appearTime = Calendar.getInstance().getTimeInMillis();
    }

    public Tuple(final Tuple tuple) {
        this.fields = tuple.getFields();
        this.seq = seq;
        appearTime = Calendar.getInstance().getTimeInMillis();
    }

    public boolean isExpired(final long currTime) {
        if (expireTime < 0 || expireTime > currTime) {
            return false;
        }
        else {
            return true;
        }
    }

    public int getField(final int idx) {
        return fields.get(idx);
    }

    public int getTargetField() {
        return fields.get(targetFieldIdx);
    }

    public ArrayList<Integer> getFields() {
        return fields;
    }

    public int getSize() {
        return fields.size();
    }

    public Tuple setTargetFieldIdx(final int idx) {
        this.targetFieldIdx = idx;

        return this;
    }

    public int getTargetFieldIdx() {
        return targetFieldIdx;
    }

    public long getExpireTime() {
        return expireTime;
    }

    public Tuple setExpireTime(final long time) {
        this.expireTime = time;

        return this;
    }

    public Tuple setLifespan(final long lifespan) {
        expireTime = appearTime + lifespan;

        return this;
    }

    public int compareTo(Tuple that) {
        return this.fields.get(targetFieldIdx).compareTo(that.getTargetField());
    }

    public boolean equals(Tuple that) {
        return (this.seq == that.seq);
    }

    public boolean matches(Tuple that) {
        return this.fields.get(targetFieldIdx).equals(that.getTargetField());
    }

    public String toString() {
        Joiner joinerComma = Joiner.on(", ").skipNulls();

        return joinerComma.join(fields);
    }
}